package gbench.sandbox.tuple;

import static gbench.common.tree.LittleTree.Tuple2.TUP2;

import org.junit.jupiter.api.Test;

public class JunitTuple {
    
    @Test
    public void foo() {
        System.out.println(TUP2(TUP2(1,2),TUP2(3,4)).flatMap(e->e));
        System.out.println(replace("this is tom tom good","tom","jim"));
    }
    
    /**
     * 简单的替换函数
     * @param line 源字符串
     * @param target 被替换字符串
     * @param replacement 替换字符串
     * @return 在line中使用replacement替换target后的字符串
     */
    public String replace(final String line,final String target,final String replacement) {
        final int len = line.length();
        final var buffer = new StringBuffer();// 结果缓存
        int targetlen = target.length();// 被替换字符串长度
        
        int i=0;
        while(i<len) {
            final var frame = new StringBuffer();// 预读数据框
            int j=i;//  预先读取的长度
            while( j<len && (j-i+1)<=targetlen && target.startsWith(frame.toString())) frame.append(line.charAt(j++));
            final var s = frame.toString();// 业已读到的字符串
            if(s.equals(target)) {// 预先读取到了 target
                buffer.append(replacement);
            }else {// 没有预先读取到 target
                buffer.append(s);
            }//while
            i+=s.length();// 步进s的长度。
        }//while
        
        return buffer.toString();
    }
    
    /**
     * substring的演示
     */
    @Test
    public void qux() {
    	try {
    		// 返回:substring(0,0):0
	    	System.out.println("substring(0,0):"+"1234".substring(0,0).length());
	    	// 会抛出异常：StringIndexOutOfBoundsException: begin 100, end 100, length 4
	    	System.out.println("substring(100,100):"+"1234".substring(100,100).length());
    	}catch(Exception e) {
    		e.printStackTrace();
    	}
    }

}
